package com.fla.millioner.ui.support;

import com.alone1672.millioner.R;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.WindowManager;
public class AndroidUtils {
    private static final String MARKET_TEMPLATE = "market://details?id=%s";
    private static final String GET_MORE = "market://search?q=%s";

    public static void playSound(Context context, int rawId) {
        MediaPlayer mp = MediaPlayer.create(context, rawId);
        if (mp != null) {
            mp.setOnCompletionListener(new OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.release();
                }
            });
            mp.setOnPreparedListener(new OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                }
            });
            mp.start();
        }
    }

    public static void launchGooglePlay(Context context) {
        Intent playStoreIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(MARKET_TEMPLATE,
            context.getApplicationInfo().packageName)));
        context.startActivity(playStoreIntent);
    }

    public static void contactDeveloper(Context context) {
        Intent emailIntent = new Intent(Intent.ACTION_SEND);
        emailIntent.setType("plain/text");
        emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"yahor.makouski@gmail.com"});
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.app_name) + getDeviceInfo(context));
        context.startActivity(Intent.createChooser(emailIntent, "Mail app"));
    }

    public static void getMore(Context context, String keyword) {
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(GET_MORE, keyword)));
        context.startActivity(browserIntent);
    }

    public static DisplayMetrics getDisplayMetrics(Context context) {
        DisplayMetrics metrics = new DisplayMetrics();
        ((WindowManager) context.getSystemService(Activity.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
        return metrics;
    }

    public static int dpToPx(Resources resources, int dp) {
        DisplayMetrics d = resources.getDisplayMetrics();
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, d);
    }
    
    
    public static int pxToSp(Resources resources, float px) {
        DisplayMetrics d = resources.getDisplayMetrics();
        return (int) (px / d.scaledDensity);
    }
    
    public static int spToPx(Resources resources, float sp) {
        DisplayMetrics d = resources.getDisplayMetrics();
        return (int) (sp * d.scaledDensity);
    }

    public static void safeDismiss(Dialog progressDialog) {
        try {
            // when dialog is already dismissed we get IllegalArgumentException: View not attached to window manager
            // this is not "Death" exception
            progressDialog.dismiss();
        }
        catch (IllegalArgumentException e) {
            Log.e("AndroidUtils", "Cannot dismiss dialog", e);
        }
    }
    
    /**
     * Checks if the device is a tablet or a phone
     * 
     * @param context
     * @return Returns true if the device is a Tablet
     */
    public static boolean isTabletDevice(Context context) {
        // Verifies if the Generalized Size of the device is XLARGE to be
        // considered a Tablet
        boolean xlarge = ((context.getResources().getConfiguration().screenLayout & 
                            Configuration.SCREENLAYOUT_SIZE_MASK) == 
                            Configuration.SCREENLAYOUT_SIZE_XLARGE);

        // If XLarge, checks if the Generalized Density is at least MDPI
        // (160dpi)
        if (xlarge) {
            DisplayMetrics metrics = new DisplayMetrics();
            ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);

            // MDPI=160, DEFAULT=160, DENSITY_HIGH=240, DENSITY_MEDIUM=160,
            // DENSITY_TV=213, DENSITY_XHIGH=320
            if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
                    || metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
                    || metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
                    || metrics.densityDpi == DisplayMetrics.DENSITY_TV
                    || metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {

                // Yes, this is a tablet!
                return true;
            }
        }

        // No, this is not a tablet!
        return false;
    }
    
    private static String getDeviceInfo(Context context) {
        try {
            String versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
            return String.format(" (%s %s, app v. %s, android v. %s)", Build.MANUFACTURER, Build.MODEL, versionName,
                Build.VERSION.RELEASE);
        }
        catch (NameNotFoundException e) {
            throw new IllegalArgumentException("Unknown name", e);
        }
    }
}
